// pages/cart/cart.js
import { CartModel } from '../../models/CartModel.js'
import { ProductModel } from '../../models/productModel.js'
import Toast from '../../components/dist/toast/toast';
let cartmodel = new CartModel()
let Product = new ProductModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartData: [],
    selectedCounts: 0, //总的商品数
    selectedCheckCounts: 0, //总的商品数  
    account: 0,
    checked:false,
    totalPrice:0,
    change:true,
    empty:false,
    submitChecked : false,
    valid:true //用来校验购物车商品信息是否存在过期

  },
  _change:function(){
      this.setData({
        change:!this.data.change
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onLoad:function(){
    this._init()
    this._totalPrice()
    
  } ,
  onShow: function () {
    this._init()
    this._totalPrice()
    this.setData({
      submitChecked:false
    })
  },
  // 初始化数据
  _init: function() {
    let that = this 
    //每次初始化都会校验购物车数据的有效性
    cartmodel.getCartData(res => {
      this.setData({
        cartData:res
      })
    })
    let data = this.data.cartData
    for (let i = 0; i < data.length; i++) {
      this.selectComponent('.mycart'+i).onLoad()
    }
    this._isEmpty(this.data.cartData)
  },
  _isEmpty:function(cartdata){
    if(cartdata.length>0){
      this.setData({
        empty:false
      })
    }else{
      this.setData({
        empty:true
      })
    }
  },
  _checkSubmit:function(){
    let cartData = this.data.cartData
    for(let i=0;i<cartData.length;i++){
      if(cartData[i].selectStatus){
        this.setData({
          submitChecked:true
        })
      }
      if(i == cartData.length){
        this.setData({
          submitChecked:false
        })
      }
    }
  },
  // 更新商品数量
  changeCount: function (event) {
    let count = event.detail.count
    let id = event.detail.productId
    let index = this._getProductIndexById(id)
    //更新商品页面
    this.data.cartData[index].counts = count
  },
  /*更新购物车商品数据*/
  _resetCartData: function () {
    let newData = this._totalAccountAndCounts(this.data.cartData) /*重新计算总金额和商品总数*/
    this.setData({
      account: newData.account,
      selectedCounts: newData.selectedCounts,
      selectedCheckCounts: newData.selectedCheckCounts,
      cartData: this.data.cartData
    })
  },
  /*离开页面时，更新本地缓存*/
  onHide: function () {
    cartmodel.localSetStorageSync(this.data.cartData)
  },
  /*
  * 计算总金额和选择的商品总数
  * */
  _totalPrice:function(){
    let data = this.data.cartData
    let len = data.length
    let sum = 0
    for (let i = 0; i < len; i++) {
      if(data[i].selectStatus){
        //避免 0.05 + 0.01 = 0.060 000 000 000 000 005 的问题，乘以 100 *100
        sum += data[i].counts * data[i].product_sell_price*100
      }
    }
    this.setData({
      totalPrice:sum/100
    })

  },

  /*根据商品id得到 商品所在下标*/
  _getProductIndexById: function (id) {
    let data = this.data.cartData
    let len = data.length
    for (let i = 0; i < len; i++) {
      if (data[i]._id == id) {
        return i
      }
    }
  },
  delete:function(){
    this.deleteData()
    wx.showToast({
      title: '删除成功',
    })
    wx.reLaunch({
      url: '../cart/cart',
    })
  },
  /*删除商品*/
  deleteData: function () {
    let data = this.data.cartData
    let len = data.length
    let id = 0
    for (let i = 0; i < len; i++) {
       id = data[i]._id
       console.log('id',id)
      // 删除选中的商品
      if(data[i].selectStatus){
        let index = this._getProductIndexById(id)-i
        console.log('index',index)
        this.data.cartData.splice(index, 1)//删除某一项商品
         cartmodel.delete(id, res => {
          })  //内存中删除该商品
      }
    }
  },

  /*选择商品*/
  ChangeRadio:function(event){
      let id = event.detail.productId
      let status = event.detail.status
      let index = this._getProductIndexById(id)
      this.data.cartData[index].selectStatus = status
      this._totalPrice()
  },

  /*全选*/
  checkall: function (event) {
    let data = this.data.cartData
    if(event.detail){
      for (let i = 0; i < data.length; i++) {
        data[i].selectStatus = true
      }
    }else{
      for (let i = 0; i < data.length; i++) {
        data[i].selectStatus = false
      }
    }
    this.setData({
      checked:!this.data.checked
    })
    for (let i = 0; i < data.length; i++) {
      if(!this.data.checked){
        this.selectComponent('.mycart'+i).noSelect()
      }else{
        this.selectComponent('.mycart'+i).allSelect()
      }
    }
    this._totalPrice()
  },
  //校验商品信息是否过期
  checkProduct:function(cartData){
    let that = this
    for(let i=0;i<cartData.length;i++){
      Product.getProductById(cartData[i]._id, res=>{
        if(res.result == null){
          that.setData({
            valid:false
          })
          console.log('valid false',that.data.valid)
        }else{
        
        }
      })

    }
  },
  /*提交订单*/
  confirm: function () {
    
    this._checkSubmit()
    let cartData = cartmodel.getCartDataFromLocal(true)
    let p ={'_id':1}
    cartData.push(p)
    console.log('cartdata',cartData)
    this.checkProduct(cartData)
    // 1、检查是否选中购物车中的商品
    if(this.data.submitChecked){
       //2、检查选择的商品是否已被下架
      if(this.data.valid){
        wx.navigateTo({
          url: '/pages/order/order?from=cart&totalPrice='+this.data.totalPrice
        })
      }else{
        Toast.fail('您购买的商品中存在已被下架产品，请检查后下单!');
      }
    }else{
      wx.showToast({
        title: '请先选择要购买的商品',
        icon:'none'
      })
    }
   
  },
  // 订单详情
  productDetail: function (event) {
    let productId = event.detail.productId
    Product.getProductById(productId, res=>{
      if(res.result){
        wx.navigateTo({
          url: '../product/product?product_id=' + productId,
        })
      }else{
        Toast.fail('该商品已被下架，请及时删除!');
      }
  
    })
  }
})


